<template>
  <div class="add-bound-form">
    <!-- 基本信息 -->
    <div class="form-section">
      <h3>基本信息</h3>
      <el-form :model="form" :rules="rules" ref="boundForm" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="入库单号" prop="boundCode">
              <el-input v-model="form.boundCode" :disabled="isEdit" placeholder="系统自动生成"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="制单人" prop="creator">
              <el-input v-model="form.creator" placeholder="请输入制单人"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单据日期" prop="createTime">
              <el-date-picker
                v-model="form.createTime"
                type="date"
                placeholder="请选择时间"
                style="width: 100%"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="供应商" prop="supplierId">
              <el-select v-model="form.supplierId" placeholder="---请选择供应商---" style="width: 100%">
                <el-option
                  v-for="supplier in suppliers"
                  :key="supplier.supplierId"
                  :label="supplier.supplierName"
                  :value="supplier.supplierId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入库仓库" prop="warehouseId">
              <el-select v-model="form.warehouseId" placeholder="--请选择入库仓库--" style="width: 100%">
                <el-option
                  v-for="warehouse in warehouses"
                  :key="warehouse.warehouseId"
                  :label="warehouse.warehouseName"
                  :value="warehouse.warehouseId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入" type="textarea" :rows="2"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 详细入库列表 -->
    <div class="form-section">
      <div class="section-header">
        <h3>详细入库列表</h3>
        <el-button type="primary" icon="el-icon-plus" @click="handleAddMaterial">+添加</el-button>
      </div>
      
      <el-table :data="boundInfoList" border style="width: 100%; margin-bottom: 20px;">
        <el-table-column label="材料名称" width="150">
          <template slot-scope="scope">
            {{ scope.row.materialName }}
          </template>
        </el-table-column>
        <el-table-column label="品牌" width="120">
          <template slot-scope="scope">
            {{ scope.row.brand }}
          </template>
        </el-table-column>
        <el-table-column label="规格型号" width="150">
          <template slot-scope="scope">
            {{ scope.row.specificationModel }}
          </template>
        </el-table-column>
        <el-table-column label="单位" width="80">
          <template slot-scope="scope">
            {{ scope.row.unit }}
          </template>
        </el-table-column>
        <el-table-column label="成本价" width="120">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.costPrice"
              placeholder="请输入"
              @input="calculateTotal(scope.row)"
              type="number"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="数量" width="120">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.quantity"
              placeholder="请输入"
              @input="calculateTotal(scope.row)"
              type="number"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="备注" width="150">
          <template slot-scope="scope">
            <el-input v-model="scope.row.remark" placeholder="请输入"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleDeleteMaterial(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 操作按钮 -->
    <div class="form-actions">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">保存</el-button>
    </div>

    <!-- 添加材料弹窗 -->
    <AddMaterialDialog
      :visible.sync="materialDialogVisible"
      @confirm="handleMaterialConfirm"
    />
  </div>
</template>

<script>
import { boundApi } from '@/api/bound'
import { supplierApi } from '@/api/supplier'
import { warehouseApi } from '@/api/warehouse'
import AddMaterialDialog from './AddMaterialDialog.vue'

export default {
  name: 'AddBoundForm',
  components: {
    AddMaterialDialog
  },
  props: {
    boundData: {
      type: Object,
      default: null
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      submitting: false,
      suppliers: [],
      warehouses: [],
      materialDialogVisible: false,
      form: {
        boundCode: '',
        creator: '',
        createTime: '',
        supplierId: '',
        warehouseId: '',
        remark: ''
      },
      boundInfoList: [],
      rules: {
        creator: [
          { required: true, message: '请输入制单人', trigger: 'blur' }
        ],
        createTime: [
          { required: true, message: '请选择单据日期', trigger: 'change' }
        ],
        supplierId: [
          { required: true, message: '请选择供应商', trigger: 'change' }
        ],
        warehouseId: [
          { required: true, message: '请选择入库仓库', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.initForm()
    this.loadSuppliers()
    this.loadWarehouses()
    if (!this.isEdit) {
      this.generateBoundCode()
    }
  },
  methods: {
    // 初始化表单
    initForm() {
      if (this.isEdit && this.boundData) {
        this.form = { ...this.boundData }
        this.boundInfoList = this.boundData.boundInfoList || []
      } else {
        // 设置默认值
        this.form.creator = 'admin'
        this.form.createTime = this.formatDate(new Date())
      }
    },

    // 加载供应商列表
    async loadSuppliers() {
      try {
        const response = await supplierApi.getAllSuppliers()
        if (response.code === 200) {
          this.suppliers = response.data || []
        }
      } catch (error) {
        console.error('加载供应商列表失败:', error)
      }
    },

    // 加载仓库列表
    async loadWarehouses() {
      try {
        const response = await warehouseApi.getAllWarehouses()
        if (response.code === 200) {
          this.warehouses = response.data || []
        }
      } catch (error) {
        console.error('加载仓库列表失败:', error)
      }
    },

    // 生成入库单号
    async generateBoundCode() {
      try {
        const response = await boundApi.generateBoundCode()
        if (response.code === 200) {
          this.form.boundCode = response.data
        }
      } catch (error) {
        console.error('生成入库单号失败:', error)
        // 如果生成失败，使用时间戳作为单号
        this.form.boundCode = 'BD' + Date.now()
      }
    },

    // 添加材料
    handleAddMaterial() {
      this.materialDialogVisible = true
    },

    // 确认添加材料
    handleMaterialConfirm(materials) {
      materials.forEach(material => {
        this.boundInfoList.push({
          materialId: material.materialId,
          materialName: material.materialName,
          brand: material.brand,
          specificationModel: material.specificationModel,
          unit: material.unit,
          costPrice: '',
          quantity: '',
          remark: material.remark || ''
        })
      })
    },

    // 删除材料
    handleDeleteMaterial(index) {
      this.boundInfoList.splice(index, 1)
    },

    // 计算总价
    calculateTotal(row) {
      const costPrice = parseFloat(row.costPrice) || 0
      const quantity = parseFloat(row.quantity) || 0
      row.totalPrice = (costPrice * quantity).toFixed(2)
    },

    // 提交表单
    async handleSubmit() {
      try {
        await this.$refs.boundForm.validate()
        
        if (this.boundInfoList.length === 0) {
          this.$message.warning('请至少添加一个材料')
          return
        }

        this.submitting = true

        const formData = {
          ...this.form,
          boundInfoList: this.boundInfoList.map(item => ({
            materialId: item.materialId,
            costPrice: parseFloat(item.costPrice) || 0,
            quantity: parseFloat(item.quantity) || 0,
            remark: item.remark || ''
          }))
        }

        let response
        if (this.isEdit) {
          response = await boundApi.updateBound(formData)
        } else {
          response = await boundApi.addBound(formData)
        }

        if (response.code === 200) {
          this.$message.success(this.isEdit ? '修改成功' : '新增成功')
          this.$emit('success')
        } else {
          this.$message.error(response.message || '操作失败')
        }
      } catch (error) {
        console.error('提交表单失败:', error)
        this.$message.error('操作失败，请稍后重试')
      } finally {
        this.submitting = false
      }
    },

    // 取消
    handleCancel() {
      this.$emit('close')
    },

    // 格式化日期
    formatDate(date) {
      const d = new Date(date)
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
    }
  }
}
</script>

<style scoped>
.add-bound-form {
  padding: 0;
  background-color: #fff;
}

.form-section {
  margin-bottom: 30px;
  padding: 20px;
  background-color: #fff;
}

.form-section:first-child {
  border-bottom: 1px solid #ebeef5;
}

.form-section h3 {
  margin-bottom: 20px;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
  padding-bottom: 10px;
  border-bottom: 2px solid #409eff;
  display: inline-block;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.section-header h3 {
  margin: 0;
  border-bottom: none;
  padding-bottom: 0;
}

.section-header .el-button {
  height: 36px;
  padding: 0 20px;
  border-radius: 4px;
  font-size: 14px;
}

.section-header .el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
}

.section-header .el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

/* 表单样式 */
.el-form {
  padding: 20px 0;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-form-item__label {
  color: #606266;
  font-weight: 500;
  font-size: 14px;
}

.el-input__inner,
.el-textarea__inner,
.el-select .el-input__inner {
  height: 36px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  font-size: 14px;
}

.el-input__inner:focus,
.el-textarea__inner:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.el-textarea {
  height: auto;
}

.el-textarea__inner {
  min-height: 60px;
  resize: vertical;
}

/* 表格样式 */
.el-table {
  border-radius: 4px;
  overflow: hidden;
}

.el-table th {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
  border-bottom: 1px solid #ebeef5;
}

.el-table td {
  border-bottom: 1px solid #f0f0f0;
}

.el-table tr:hover > td {
  background-color: #f5f7fa;
}

.el-table .el-input {
  width: 100%;
}

.el-table .el-input__inner {
  height: 32px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.el-table .el-input__inner:focus {
  border-color: #409eff;
}

.el-table .el-button--text {
  color: #409eff;
  padding: 0;
  font-size: 14px;
}

.el-table .el-button--text:hover {
  color: #66b1ff;
}

/* 操作按钮样式 */
.form-actions {
  text-align: center;
  padding: 20px;
  background-color: #f9f9f9;
  border-top: 1px solid #ebeef5;
  margin: 0 -20px -20px;
}

.form-actions .el-button {
  margin: 0 10px;
  min-width: 100px;
  height: 40px;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
}

.form-actions .el-button--primary {
  background-color: #67c23a;
  border-color: #67c23a;
}

.form-actions .el-button--primary:hover {
  background-color: #85ce61;
  border-color: #85ce61;
}

.form-actions .el-button--default {
  background-color: #fff;
  border-color: #dcdfe6;
  color: #606266;
}

.form-actions .el-button--default:hover {
  background-color: #ecf5ff;
  border-color: #b3d8ff;
  color: #409eff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .add-bound-form {
    padding: 0;
  }
  
  .form-section {
    padding: 15px;
  }
  
  .el-row {
    margin: 0 !important;
  }
  
  .el-col {
    padding: 0 !important;
    margin-bottom: 15px;
  }
  
  .section-header {
    flex-direction: column;
    align-items: stretch;
    gap: 15px;
  }
  
  .form-actions {
    margin: 0 -15px -15px;
    padding: 15px;
  }
}
</style>
